package com.atguigu.flinksql.day10;

import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * ClassName: Test04_StreamToTable_ET
 * Package: com.atguigu.flinksql.day10
 * Description:
 *             添加数据添加事件时间，要先设置watermark，获取时间戳
 * @Author ChenJun
 * @Create 2023/4/18 11:45
 * @Version 1.0
 */
public class Test04_StreamToTable_ET {
    public static void main(String[] args) {

        //1. 创建运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2. 从端口读取数据 转换为JavaBean
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = streamSource.map(line -> {
            String[] split = line.split(",");
            return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
        });

        //TODO 3. 提取时间戳生成WaterMark
        SingleOutputStreamOperator<WaterSensor> waterSensorWithWMDS = waterSensorDS.assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs() * 1000;
                    }
                }));

        //TODO 4.将流转换为动态表  同时添加事件时间
        Table table = tableEnv.fromDataStream(waterSensorWithWMDS,$("id"),$("ts"), $("vc"),$("rt").rowtime());

        //TODO 5.直接打印
        table.execute().print();

    }
}
